import time

from robot.api import logger
from selenium.webdriver.common.by import By

from .antd_page_element import AntdPageElement
from ...common.element_function import ElementFunction
from ...common.ui.PageElement import PageElement
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Upload(AntdPageElement):

    def setValue(self, value=None):
        self.value = value

        input_element = self._find_file_input_element()
        input_element.send_keys(value)
        self._wait_upload_done()

    def _find_file_input_element(self):
        # 找到输入框
        element = self._get_web_element()

        if element.tag_name == 'input':
            return element

        input_element = element.find_element(By.TAG_NAME, 'input')
        return input_element

    def _wait_upload_done(self, timeout=30):
        # 整个页面查找，因为假设页面上之前所有上传都是成功的
        upload_list_elements = self._driver.find_elements(By.CSS_SELECTOR, 'div.ant-upload-list-item')
        end_time = time.time() + timeout
        is_done = False
        while True:
            logger.debug("waiting the upload complete...")
            if self._check_upload_done(upload_list_elements):
                is_done = True
                break
            time.sleep(1)
            if time.time() > end_time:
                break

        if not is_done:
            raise TestException(ErrorCode.UPLOAD_FAILED, value=self.value)

    def _check_upload_done(self, upload_list_elements):
        if len(upload_list_elements) <= 0:
            logger.warn("Can't find the upload file list element, you may be check the file upload done by your self.")
            return True
        # 假设页面之前显示的上传结果都是成功的
        for element in upload_list_elements:
            class_attribute = element.get_attribute('class')
            if 'ant-upload-list-item-error' in class_attribute:
                raise TestException(ErrorCode.UPLOAD_FAILED, value=self.value)
            if 'ant-upload-list-item-done' not in class_attribute:
                return False
        return True

    def get_identification(self):
        identification = {'class': ['ant-upload'],
                          }
        return identification
